﻿using System;
using System.Collections.Generic;
using System.Text;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Expressions;
using OpenLS.Spreadsheet.Extensibility;
using OpenLS.Spreadsheet.Parsing;
using OpenLS.Spreadsheet.Serialization;

namespace OpenLS.Spreadsheet
{
    public class SparkLine: IOfficeXmlSerializable
    {
        private string f;
        //private string sqref;
        private Cell _target;
        internal const string xmlName = @"sparkline";

        public string Formula
        {
            get { return f; }
            set { f = value; }
        }

        public Cell Target
        {
            get {
                return _target;
            }
            set {
                _target = value;
            }
        }

        public void ReadXml(ReadContext context)
        {
            using (var rc = context.Read(xmlName))
            {
               // rc.PassAttributes();
               // var rc2 = rc.SwitchNamespace(SpreadsheetConstants.ExcelMainNamespace.NamespaceUri,false);
                this.Formula = rc.ReadOptionalElementString(SpreadsheetConstants.ExcelMainNamespace + "f");
                string sqref = rc.ReadElementString(SpreadsheetConstants.ExcelMainNamespace + "sqref");
                var worksheet = context.GetData<Worksheet>();
                context.GetData<WorkbookResolver>().ResolveActions.Add(() => this.Target = worksheet.GetRangeReference(sqref).Range.FirstCell);
            }
        }

        public void WriteXml(WriteContext context)
        {
            using (var rc = context.Write(xmlName))
            {
                var rc2 = rc.Switch(SpreadsheetConstants.ExcelMainNamespace);
                rc2.WriteOptionalElementString("f", this.Formula);
                string sqref = new SingleCellRange(Target).ToReference().FullLabel;
                rc2.WriteElementString("sqref", sqref);
            }
        }

        private IRange GetRange(EvaluationContext context)
        {
            var expressionParser = new ExpressionParser(Target.Worksheet, Target, LocalizationMode.NonLocalized, CellReferenceMode.Dynamic);
            var expression = expressionParser.Expression("="+Formula);
            if (expression is CellEnumeratorExpression)
            {
                return   ((CellEnumeratorExpression)expression).GetCellsValue(context).ToRange();
            }
            throw new NotSupportedException();
        }
        internal IEnumerable<object> GetValues()
        {
            var range = GetRange(new CellEvaluationContext(Target));
            for (int row = 0; row < range.RowSpan; row++)
            {
                for (int column = 0; column < range.ColumnSpan; column++)
                {
                    yield return range[row, column].Value;
                }

            }
        }
    }
}
